package be.phl.mycinema;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import be.phl.mycinema.classes.Gebruiker;

import com.google.gson.Gson;

public class LoginActivity extends Activity implements OnClickListener {

	private final static String TAG = "LOGIN ACTIVITY";
	private Button btnLogin;
	private Button btnRegistreer;
	private TextView txtEmail;
	private TextView txtWachtwoord;
	private Context myContext = this;
	private View backgroundImage;
	private Drawable bg;
	private SharedPreferences prefs;
	private Editor prefsEditor;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);

		prefs = getSharedPreferences("be.phl.mycinema.userinfo", MODE_PRIVATE);

		if (!prefs.getString("Email", "False").equals("False")) {
			Log.d(TAG, "User is already logged in!");

			Intent i = new Intent(this, MainActivity.class);
			startActivity(i);
		}

		btnLogin = (Button) findViewById(R.id.btn_Login);
		btnRegistreer = (Button) findViewById(R.id.btnRegistreer);
		backgroundImage = findViewById(R.id.login_background);
		bg = backgroundImage.getBackground();
		bg.setAlpha(40);
		
		btnLogin.setOnClickListener(this);
		btnRegistreer.setOnClickListener(this);
	}
    
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_Login:
			
			txtEmail = (TextView) findViewById(R.id.login_txtEmail);
			txtWachtwoord = (TextView) findViewById(R.id.login_txtWachtwoord);
			
			if (txtEmail.getText().toString().equals("") || txtWachtwoord.getText().toString().equals("")) {
				Toast.makeText(this, "Vul een geldig e-mailadres en wachtwoord in!", Toast.LENGTH_LONG).show();
				return;
			} else {
				if (Utils.isNetworkAvailable((ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE))) {
					if (Utils.isWebserviceAvailable()) {
						String url = String.format(Utils.WEBSERVICE_BASE_ADDRESS + "/login?email=%s&ww=%s", txtEmail.getText(), txtWachtwoord.getText());
						Log.d(TAG, "logging in...");
						new LoginTask().execute(url);
					} else {
						Toast.makeText(getBaseContext(), "De server is niet bereikbaar, probeer later opnieuw.", Toast.LENGTH_LONG).show();
					}
				} else {
					Toast.makeText(myContext, "Er is geen internetverbinding beschikbaar!", Toast.LENGTH_LONG).show();
				}
			}
			break;
			
		case R.id.btnRegistreer:
			Log.d(TAG, "Starting registratie..");
			Intent i = new Intent(this, RegistratieActivity.class);
			startActivity(i);
			break;
		}
	}

	private class LoginTask extends AsyncTask<String, Void, Boolean> {

		@Override
		protected Boolean doInBackground(String... urls) {
			try {
				URL url = new URL(urls[0]);
				HttpURLConnection con = (HttpURLConnection) url.openConnection();

				String json = Utils.readJsonFromServer(con.getInputStream());
				Gson g = new Gson();

				if (!(json.toString().equals("False") || json == null)) {
					Gebruiker gebruiker = g.fromJson(json, Gebruiker.class);

					if (gebruiker.getGebruiker_ID() != null) {

						Log.d(TAG, "Creating shared prefs..");

						prefsEditor = prefs.edit();
						prefsEditor.clear();
						prefsEditor.putString("Gebruiker_ID",gebruiker.getGebruiker_ID());
						prefsEditor.putString("Email", gebruiker.getEmail());
						prefsEditor.putString("Voornaam",gebruiker.getVoornaam());
						prefsEditor.putString("Achternaam",gebruiker.getAchternaam());
						prefsEditor.putString("Geboortedatum",gebruiker.getGeboortedatum());
						prefsEditor.apply();

						Log.d(TAG, prefs.getString("Email", "False"));

						return true;
					}
				}
			} catch (MalformedURLException e) {
				Log.e(TAG, e.getMessage());
			} catch (IOException e) {
				Log.e(TAG, e.getMessage());
			}
			return false;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			if (result) {
				Log.d(TAG, "Login succes.");
				Intent i = new Intent(myContext, MainActivity.class);
				startActivity(i);
			} else {
				Log.d(TAG, "Login failed..");
				Toast.makeText(myContext, "Foutief e-mailadres of wachtwoord.", Toast.LENGTH_LONG).show();
				txtEmail = (EditText) findViewById(R.id.login_txtEmail);
				txtWachtwoord = (EditText) findViewById(R.id.login_txtWachtwoord);
				txtWachtwoord.setText("");
				txtEmail.requestFocus();
			}
		}
	}
	
    @Override
    public void onBackPressed() {
    	//Back button disabled
    }
}
